package com.hunt.service.impl;

import com.github.pagehelper.PageHelper;
import com.hunt.dao.*;
import com.hunt.model.dto.*;
import com.hunt.model.dto.LoginInfo_new;
import com.hunt.model.dto.UserLevel;
import com.hunt.model.entity.*;
import com.hunt.service.ManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.*;


@Service
@Transactional
public class ManagementServiceImpl implements ManagementService {
    private static final Logger log = LoggerFactory.getLogger(ManagementService.class);

    @Autowired
    private ManagementMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserPermissionMapper sysUserPermissionMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysLoginStatusMapper sysLoginStatusMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private AddressInfoMapper addressInfoMapper;


    @Override
    public PageInfo selectPage(int page, int rows, String sort, String order, String loginName, String zhName, String email, String phone, String address) {
        int counts = sysUserMapper.selectCounts(sort, order, loginName, zhName, email, phone, address);
        page = (page-1) * rows;
        List<SysUser> sysUsers = sysUserMapper.selectAll(page, rows, order, loginName, zhName, email, phone, address);
        PageInfo pageInfo = new PageInfo(counts, sysUsers);
        return pageInfo;
    }

    /**
     * 新增User 和 userRoles
     * @param user
     * @param jobIds
     * @return
     */
    @Override
    public long insertUser(SysUser user, String jobIds) {
        sysUserMapper.insert(user);
        pubSaveUpdateUserRole(user, jobIds);
        return user.getId();
    }

    /**
     * 修改User 和 userRoles
     * @param user
     * @param jobIds
     */
    @Override
    public void updateUser(SysUser user, String jobIds) {
        sysUserMapper.update(user);
        sysUserRoleMapper.deleteUserRoleByUserId(user.getId());
        pubSaveUpdateUserRole(user, jobIds);
    }

    /**
     * 新增 或者 修改User 的 抽象方法
     * @param user
     * @param jobIds
     */
    private void pubSaveUpdateUserRole(SysUser user, String jobIds) {
        String[] jobIdArray = jobIds.split(",");
        for (String jobId : jobIdArray) {
            if (null == jobId || "".equals(jobId.trim())){
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setSysUserId(user.getId());
            sysUserRole.setSysRoleId(Long.valueOf(jobId));
            sysUserRole.setIsFinal(1);
            Date date = new Date();
            sysUserRole.setCreateTime(date);
            sysUserRole.setUpdateTime(date);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    @Override
    public boolean isExistLoginName(String loginName) {
        return sysUserMapper.selectByLoginName(loginName);
    }

    @Override
    public SysUser selectById(long id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public PageInfo selectAccountPage(int page, int rows, String sort, String order, String userid, String username, Integer moneyfrom,Integer moneyto, String phone, String address) {
        int counts = sysUserMapper.selectAccountCounts(sort, order, userid, username, moneyfrom,moneyto, phone, address);
        PageHelper.startPage(page, rows);
        List<LoginInfo_new> sysUsers = sysUserMapper.selectAllAccount(sort, order, userid, username,moneyfrom,moneyto, phone, address);
        PageInfo pageInfo = new PageInfo(counts, sysUsers);
        return pageInfo;
    }
    @Override
    public PageInfo selectAccountPageforcustomer(int page, int rows, String sort, String order, String userid, String username, String phone) {
        int counts = sysUserMapper.selectAccountCountsforcustomer(sort, order, userid, username, phone);
        PageHelper.startPage(page, rows);
        List<LoginInfo_new> sysUsers = sysUserMapper.selectAllAccountforcustomer(sort, order, userid, username, phone);
        PageInfo pageInfo = new PageInfo(counts, sysUsers);
        return pageInfo;
    }
    @Override
    public void updateUser(SysUser user) {
        sysUserMapper.update(user);
    }

    @Override
    public SysUser selectByLoginName(String loginName) {
        return sysUserMapper.selectUserByLoginName(loginName);
    }

    @Override
    public LoginInfo_new_child selectByLoginName_new(String userid) {
        return sysUserMapper.selectUserByLoginName_new(userid);
    }


    @Override
    public LoginInfo login(SysUser user, Serializable id, int platform) {
        //log.debug("sessionId is:{}", id.toString());
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user, loginInfo);
        List<SysUserPermission> userPermissions = sysUserPermissionMapper.selectByUserId(user.getId());
        List<SysPermission> permissions = new ArrayList<>();
        for (SysUserPermission userPermission : userPermissions) {
            SysPermission sysPermission = sysPermissionMapper.selectById(userPermission.getSysPermissionId());
            permissions.add(sysPermission);
        }
        List<SysUserRole> userRoleOrganizations = sysUserRoleMapper.selectByUserId(user.getId());
        loginInfo.setJobs(userRoleOrganizations);

        SysLoginStatus newLoginStatus = new SysLoginStatus();
        newLoginStatus.setSysUserId(user.getId());
        newLoginStatus.setSysUserZhName(user.getZhName());
        newLoginStatus.setSysUserLoginName(user.getLoginName());
        newLoginStatus.setSessionId(id.toString());
        newLoginStatus.setSessionExpires(new DateTime().plusDays(30).toDate());
        newLoginStatus.setPlatform(platform);

        SysLoginStatus oldLoginStatus = sysLoginStatusMapper.selectByUserIdAndPlatform(user.getId(), platform);
        if (oldLoginStatus != null) {
            if (!oldLoginStatus.getSessionId().equals(id.toString())) {
                redisTemplate.opsForValue().getOperations().delete(oldLoginStatus.getSessionId());
            }
            oldLoginStatus.setStatus(2);
            sysLoginStatusMapper.update(oldLoginStatus);
            newLoginStatus.setLastLoginTime(oldLoginStatus.getCreateTime());
        }
        sysLoginStatusMapper.insert(newLoginStatus);
        return loginInfo;
    }

    @Override
    public LoginInfo_new login_new(LoginInfo_new user, Serializable id, int platform) {

        LoginInfo_new loginInfo = new LoginInfo_new();
        BeanUtils.copyProperties(user, loginInfo);


        return loginInfo;
    }


    @Override
    public boolean isExistLoginNameExcludeId(long id, String loginName) {
        return sysUserMapper.isExistLoginNameExcludeId(id, loginName);
    }

    @Override
    public void deleteById(long id) {
        sysUserMapper.deleteById(id);
        sysUserRoleMapper.deleteUserRoleByUserId(id);
    }

    @Override
    public UserLevel getUserLevelById(String userid, String userlevel) {
        return sysUserMapper.selectUserLevelById(userid, userlevel);
    }

    @Override
    public boolean isExistUserId(String userid) {
        return sysUserMapper.selectIsExByUserId(userid);
    }

    @Override
    public boolean isExistFBUserId(String userid) {
        return sysUserMapper.selectIsExFBByUserId(userid);
    }

    @Override
    public long insertAccount(LoginInfo_new mUserinfo) {
        sysUserMapper.insertAccount(mUserinfo);
        return 0;
    }
    @Override
    public long insertAccountChannel2(LoginInfo_new mUserinfo) {
        sysUserMapper.insertAccountChannel2(mUserinfo);
        return 0;
    }

    @Override
    public UserLevel getUserLevelByid(String userlevel) {
        return sysUserMapper.selectUserLevel(userlevel);
    }

    @Override
    public void updateAccount(LoginInfo_new userinfo) {
        sysUserMapper.updateAccount(userinfo);
    }

    @Override
    public void deleteAccountById(String userid) {
        sysUserMapper.deleteAccountByUserId(userid);
    }

    @Override
    public void resetAllAccountState() {
        sysUserMapper.resetAllAccountState();
    }

    @Override
    public List<MechanismTrend> getMechanismTrendFive() {
        return sysUserMapper.getMechanismTrwenFice5();

    }

    @Override
    public PageInfo getServerState() {

        PageHelper.startPage(1, 30);
        List<ServerstateDto> serverList = sysUserMapper.getServerState();
        //取得在线用户列表
        List<LoginInfo_new> mOnlUsers = sysUserMapper.getOnlineUsers();
        ServerstateDto mAllEntity = new ServerstateDto();
        mAllEntity.setServername("总数");
        mAllEntity.setOnlinenumber(String.valueOf(mOnlUsers.size()));
        //加入到列表末尾
        serverList.add(mAllEntity);
        Map<String,Integer> map = new LinkedHashMap<>();
        for (ServerstateDto serverstateDto : serverList) {
            if (serverstateDto.getServername().equals("总数"))
                continue;
            map.put(serverstateDto.getServerid(),0);
        }
        for (LoginInfo_new mOnlUser : mOnlUsers) {
            if (null != mOnlUser.getServerid() && !"".equals(mOnlUser.getServerid())){
                Integer serverOnlineNum = map.get(mOnlUser.getServerid());
                if (serverOnlineNum == null){
                    continue;
                }
                map.put(mOnlUser.getServerid(),serverOnlineNum+1);
            }
        }
        for (ServerstateDto serverstateDto : serverList) {
            if (serverstateDto.getServername().equals("总数"))
                continue;
            serverstateDto.setOnlinenumber(String.valueOf(map.get(serverstateDto.getServerid())));
        }
        return new PageInfo(serverList.size(), serverList);
    }

    @Override
    public List<ServerstateDto> getServerStateInfo() {
        List<ServerstateDto> serverStateInfos = sysUserMapper.getServerState();
        return serverStateInfos;
    }

    @Override
    public List<LoginInfo_new> getOnlineUsers() {
        return sysUserMapper.getOnlineUsers();
    }

    @Override
    public List<ServerstateDto> getServerMessage(String serverid) {
        return sysUserMapper.getServerMessage(serverid);
    }

    @Override
    public List<ServerstateDto> getFastServerMessage() {
        return sysUserMapper.getFastServerMessage();
    }

    @Override
    public List<AddressInfo> findneedarea() {
        return addressInfoMapper.findneedarea();
    }

    @Override
    public List<AddressInfo> findneedareabycode(Integer id) {
        String i=String.valueOf(id);
         String i1=i.substring(0,2);
        return addressInfoMapper.findneedareabycode(Integer.valueOf(i1));
    }

    @Override
    public List<AddressInfo> findallcity() {
        return addressInfoMapper.findallcity();
    }

    @Override
    public String getKaiHuTime(String userid) {
        return sysUserMapper.getKaiHuTime(userid);
    }

}
